<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
    public function __construct(){
        parent::__construct();
          
        $this->model = $this->getModel();
        $this->aut = new bgAuthorize();
    }    
    public function display($cachable = false, $urlparams = false) {
        parent::display($cachable, $urlparams);
    }
            
    /**
	*Save temp information Town
	*/
    public function savetemp(){
        // get data form
        $data = &JRequest::getVar('jform');
        //Check exist TOWN_CODE
        if($this->getModel()->checkExistID($data['TOWN_CODE'])){
            $addNew = false;
        }
        else{
            $addNew = true;
        }
        if(empty($data['TOWN_CODE'])){
                    $error = "ＩＤを入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['TOWN_NAME'])){
                    $error = "市町村名を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['TOWN_KANA'])){
                    $error = "市町村名（カナ）を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }else{       
            //Check null or 0 for Money
            $data['TOWN_POPU'] = $data['TOWN_POPU']==='' ? null : $data['TOWN_POPU'];
            $data['TOWN_HOUS'] = $data['TOWN_HOUS']==='' ? null : $data['TOWN_HOUS'];
            $data['TOWN_AREA'] = $data['TOWN_AREA']==='' ? null : $data['TOWN_AREA'];
            $data['TOWN_DENS'] = $data['TOWN_DENS']==='' ? null : $data['TOWN_DENS'];
            
            $data['TOWN_DATE'] = date('Y-m-d H:i:s');
            $data['TOWN_FLAG'] = 1;
            $data['TOWN_WEBF'] = 0;
            $data['TOWN_DBSY'] = 0;
            
            $data['TOWN_USER_CREATE'] = $this->aut->getUserID();
            
            if($this->model->save($data, $addNew)){
                $this->setRedirect('index.php?option=com_town');
            }
            else{
                $error = "エラー！データが記録されません。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($error, 'error');
            }
        }
        parent::display();
    }
    
    /**
	*Save information Town
	*/
    public function save(){
        // get data form
        $data = &JRequest::getVar('jform');
        if($this->getModel()->checkExistID($data['TOWN_CODE'])){
            $addNew = false;
        }
        else{
            $addNew = true;
        }
        if(empty($data['TOWN_CODE'])){
                    $error = "ＩＤを入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['TOWN_NAME'])){
                    $error = "市町村名を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }elseif(empty($data['TOWN_KANA'])){
                    $error = "市町村名（カナ）を入力してください。";
                    JRequest::setVar('task','error');
                    JFactory::getApplication()->enqueueMessage($error, 'error');
        }else{  
            //Check null or 0 for Money
            $data['TOWN_POPU'] = $data['TOWN_POPU']==='' ? null : $data['TOWN_POPU'];
            $data['TOWN_HOUS'] = $data['TOWN_HOUS']==='' ? null : $data['TOWN_HOUS'];
            $data['TOWN_AREA'] = $data['TOWN_AREA']==='' ? null : $data['TOWN_AREA'];
            $data['TOWN_DENS'] = $data['TOWN_DENS']==='' ? null : $data['TOWN_DENS'];
            
            $data['TOWN_DATE'] = date('Y-m-d H:i:s');
            $data['TOWN_FLAG'] = 1;
            $data['TOWN_WEBF'] = 1;
            $data['TOWN_DBSY'] = 0;
            
            $data['TOWN_USER_CREATE'] = $this->aut->getUserID();
            
            if($this->model->save($data, $addNew)){
                $this->setRedirect('index.php?option=com_town');
            }
            else{
                //JError::raiseError(500, 'Error ! Can\t save');
                //$error = "Error! Can't save!";
                $error = "エラー！データが記録されません。";
                JRequest::setVar('task','');
                JFactory::getApplication()->enqueueMessage($error, 'error');
            }
        }
        parent::display();

    }
    
    /**
	*Delete information Town
	*/
    public function remove(){
        $cid = JRequest::getVar('cid');
        if($this->model->remove($cid)){
            $this->setRedirect('index.php?option=com_town');
        }else{
            //JError::raiseError(500, 'Error ! Can\'t delete' );
            $error = "エラー！データが削除されません。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($error, 'error');
        }
    }
    
    /**
	*Search TOWN_POST 
    *Return TOWN_PREF_CODE,TOWN_ADD1,TOWN_ADD2 
	*/
   /* public function searchTOWN_POST()
    {
        $message = '<font color="#ff3333">';
        $str = JRequest::getVar('TOWN_POST');
        $TOWN_POST = substr($str,0,3);
        $TOWN_POST .= substr($str,4);
       	$err_message = ZipSearch::CheckValueZIP($TOWN_POST);
        if($err_message == '') {
        	$result = ZipSearch::GetAddress($TOWN_POST);
            if($result['result']['result_values_count']) {
       		   $result_single = ZipSearch::ChangeSingle($result['values']);
        	   if($result_single['address_kana'] == 'none') {
        	       $result_single['address_kana'] = '';
        	   }
        	   if($result_single['address'] == 'none') {
        	       $result_single['address'] = '';
     		  }
            $PREF_CODE = $this->model->getPREF_CODE($result_single[state]);
            echo "<tr>
                <td style='text-align: right;font-size: 1.091em;padding-right:5px;line-height:30px'>都道府県</td>
                <td><select name='jform[TOWN_PREF_CODE]' class='inputbox_town'>";
                    foreach($this->model->getPREF() as $pref){
                        $selected = $result_single[state] == $pref->PREF_NAME ? 'selected' : '';
                        echo "<option $selected value='$pref->PREF_CODE'>$pref->PREF_NAME</option>";
                    }
            echo "</select></td>
                    <td style='text-align: right;font-size: 1.091em;padding-right:5px;'></td>
                    <td></td>
                </tr>";
            echo "
            <tr>
                <td style='text-align: right;font-size: 1.091em;padding-right:5px;width:220px;line-height:30px'>住所１</td>
                <td style='width: 42%;'><input type='text' name='jform[TOWN_ADD1]' class='inputbox_town' value='$result_single[city]$result_single[address]' /></td>
                <td style='text-align: right;font-size: 1.091em;padding-right:5px;width:90px;line-height:30px'>住所2</td>
                <td style='width:239px'><input type='text' name='jform[TOWN_ADD2]' class='inputbox_town' /></td> 
            </tr>";
            }
  	        else {
        		$message .= '該当する住所がありませんでした。'.'</font>';
                echo $message;
       		}
       	}
       	else {
      		$message .= $err_message.'</font>';
            echo $message;
       	}
        $app = &JFactory::getApplication();
        $app->close();
    }*/

    public function searchTOWN_POST(){
        $data = array();
        $str = JRequest::getVar('TOWN_POST');
        $TOWN_POST = substr($str,0,3);
        $TOWN_POST .= substr($str,4);
        $err_message = ZipSearch::CheckValueZIP($TOWN_POST);
        if($err_message == '') {
            $result = ZipSearch::GetAddress($TOWN_POST);
            if($result['result']['result_values_count']) {
                $result_single = ZipSearch::ChangeSingle($result['values']);
                if($result_single['address_kana'] == 'none') {
                    $result_single['address_kana'] = '';
                }
                if($result_single['address'] == 'none') {
                    $result_single['address'] = '';
                }
                $PREF_CODE = $this->model->getPREF_CODE($result_single[state]);
                $data['pref'] = $result_single['state'];
                $data['city'] = $result_single['city'];
                $data['address'] = $result_single['address'];
                $data['message'] = "ok";
            }
            else {
                $data['message'] .= '該当する住所がありませんでした。';
            }
        }
        else {
            $data['message'] = $err_message;
        }
        echo json_encode($data);
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    /**
	*Export data from mysql (table TOWN) to file csv
	*/
    public function export_csv(){
        if(HelperBG::export_csv()){
            $this->setRedirect('index.php?option=com_town');
        }
        else{
            //JError::raiseError(500, 'Error ! Can\t export file CSV');
            $error = "エラー！CSVファイルが出力されません。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($error, 'error');
        }
        parent::display();
    }
    
    /**
	*Dong bo data from mysql (table TOWN) to file csv
	*/
    public function dongbo_csv_town(){
        if(HelperBG::dongbo_csv_town()){
            $this->setRedirect('index.php?option=com_town');
        }
        else{
            //JError::raiseError(500, 'Error ! Can\t export file CSV');
            $error = "エラー！CSVファイルが出力されません。";
            JRequest::setVar('task','');
            JFactory::getApplication()->enqueueMessage($error, 'error');
        }
        parent::display();
    }
}